<script setup>
import { ref, onMounted, computed } from 'vue'
import ApiService from '@/services/ApiService'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { hasPermission } from '@/utils/auth'
import { Plus, Loading, OfficeBuilding, FolderOpened, Document, Search } from '@element-plus/icons-vue'

const authStore = useAuthStore()
const organizations = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentOrganization = ref(null)
const editMode = ref(false)
const createOrgDialog = ref(false)
const searchText = ref('')
const selectedOrgId = ref(null)

// 组织表单
const orgForm = ref({
  id: '',
  name: '',
  code: '',
  description: '',
  type: 'department',
  parent: null
})

// 组织类型选项
const orgTypes = [
  { value: 'company', label: '公司' },
  { value: 'department', label: '部门' },
  { value: 'team', label: '团队' }
]

// 检查权限 - 只有管理员可以管理组织
const canManageOrgs = computed(() => hasPermission('*'))

// 转换组织列表为树形结构
const treeData = computed(() => {
  // 首先创建一个映射，用于快速查找
  const orgMap = new Map()
  organizations.value.forEach(org => {
    orgMap.set(org.id, { ...org, children: [] })
  })
  
  // 构建树结构
  const tree = []
  organizations.value.forEach(org => {
    const node = orgMap.get(org.id)
    
    if (!org.parent) {
      // 根节点，直接加入树中
      tree.push(node)
    } else if (orgMap.has(org.parent)) {
      // 子节点，加入到父节点的children数组中
      orgMap.get(org.parent).children.push(node)
    }
  })
  
  return tree
})

// 获取当前选中组织的详细信息
const selectedOrg = computed(() => {
  if (!selectedOrgId.value) return null
  return organizations.value.find(org => org.id === selectedOrgId.value)
})

// 当前选中组织的子组织
const childOrganizations = computed(() => {
  if (!selectedOrgId.value) {
    // 如果没有选中任何组织，则返回所有根组织
    return organizations.value.filter(org => !org.parent)
  }
  // 否则返回选中组织的直接子组织
  return organizations.value.filter(org => org.parent === selectedOrgId.value)
})

// 根据搜索文本过滤组织
const filteredOrganizations = computed(() => {
  if (!searchText.value) {
    return childOrganizations.value
  }
  
  const searchLower = searchText.value.toLowerCase()
  return organizations.value.filter(org => 
    org.name.toLowerCase().includes(searchLower) || 
    org.code.toLowerCase().includes(searchLower) ||
    org.description.toLowerCase().includes(searchLower)
  )
})

// 处理树节点点击
const handleNodeClick = (data) => {
  selectedOrgId.value = data.id
}

// 加载所有组织
const loadOrganizations = async () => {
  loading.value = true
  try {
    // 模拟API调用 - 在实际应用中应该从API获取
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 示例数据
    organizations.value = [
      {
        id: 'org-1',
        name: '总公司',
        code: 'HQ',
        description: '总部机构',
        type: 'company',
        parent: null,
        createdAt: '2023-01-01T00:00:00Z'
      },
      {
        id: 'org-2',
        name: '技术部',
        code: 'TECH',
        description: '技术研发部门',
        type: 'department',
        parent: 'org-1',
        createdAt: '2023-01-02T00:00:00Z'
      },
      {
        id: 'org-3',
        name: '研发一组',
        code: 'DEV1',
        description: '产品研发团队一组',
        type: 'team',
        parent: 'org-2',
        createdAt: '2023-01-03T00:00:00Z'
      },
      {
        id: 'org-4',
        name: '研发二组',
        code: 'DEV2',
        description: '产品研发团队二组',
        type: 'team',
        parent: 'org-2',
        createdAt: '2023-01-04T00:00:00Z'
      },
      {
        id: 'org-5',
        name: '市场部',
        code: 'MKT',
        description: '市场推广部门',
        type: 'department',
        parent: 'org-1',
        createdAt: '2023-01-05T00:00:00Z'
      },
      {
        id: 'org-6',
        name: '市场策划组',
        code: 'PLAN',
        description: '市场策划团队',
        type: 'team',
        parent: 'org-5',
        createdAt: '2023-01-06T00:00:00Z'
      },
      {
        id: 'org-7',
        name: '销售部',
        code: 'SALES',
        description: '销售部门',
        type: 'department',
        parent: 'org-1',
        createdAt: '2023-01-07T00:00:00Z'
      }
    ]
    
    loading.value = false
  } catch (error) {
    ElMessage.error('加载组织列表失败')
    loading.value = false
  }
}

// 打开创建组织对话框
const openCreateDialog = (parentId = null) => {
  editMode.value = false
  orgForm.value = {
    id: '',
    name: '',
    code: '',
    description: '',
    type: 'department',
    parent: parentId || selectedOrgId.value
  }
  createOrgDialog.value = true
}

// 在选中组织下创建子组织
const createChildOrg = () => {
  if (!selectedOrgId.value) {
    ElMessage.warning('请先选择一个父组织')
    return
  }
  openCreateDialog(selectedOrgId.value)
}

// 打开编辑组织对话框
const openEditDialog = (org) => {
  editMode.value = true
  currentOrganization.value = org
  orgForm.value = {
    id: org.id,
    name: org.name,
    code: org.code,
    description: org.description,
    type: org.type,
    parent: org.parent
  }
  createOrgDialog.value = true
}

// 创建或更新组织
const saveOrganization = async () => {
  // 表单验证
  if (!orgForm.value.name || !orgForm.value.code) {
    ElMessage.warning('请填写组织名称和组织代码')
    return
  }
  
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (editMode.value) {
      // 编辑现有组织
      const index = organizations.value.findIndex(o => o.id === orgForm.value.id)
      if (index !== -1) {
        organizations.value[index] = { 
          ...orgForm.value,
          createdAt: organizations.value[index].createdAt
        }
      }
      ElMessage.success(`组织 ${orgForm.value.name} 已更新`)
    } else {
      // 创建新组织
      const newOrg = {
        ...orgForm.value,
        id: 'org-' + Date.now(),
        createdAt: new Date().toISOString()
      }
      organizations.value.push(newOrg)
      ElMessage.success(`组织 ${newOrg.name} 已创建`)
    }
    
    createOrgDialog.value = false
    loading.value = false
  } catch (error) {
    ElMessage.error(editMode.value ? '更新组织失败' : '创建组织失败')
    loading.value = false
  }
}

// 删除组织
const deleteOrganization = (org) => {
  // 检查是否有子组织
  const hasChildren = organizations.value.some(o => o.parent === org.id)
  
  if (hasChildren) {
    ElMessage.warning('该组织下存在子组织，请先删除子组织')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除组织 "${org.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 从列表中移除组织（实际应用中应该调用API）
      organizations.value = organizations.value.filter(o => o.id !== org.id)
      
      // 如果删除的是当前选中的组织，清除选中状态
      if (selectedOrgId.value === org.id) {
        selectedOrgId.value = null
      }
      
      ElMessage.success(`组织 ${org.name} 已删除`)
      loading.value = false
    } catch (error) {
      ElMessage.error('删除组织失败')
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 获取父组织名称
const getParentName = (parentId) => {
  if (!parentId) return '无'
  const parent = organizations.value.find(o => o.id === parentId)
  return parent ? parent.name : '未知'
}

// 获取组织类型标签
const getOrgTypeLabel = (type) => {
  const typeObj = orgTypes.find(t => t.value === type)
  return typeObj ? typeObj.label : type
}

// 获取组织类型标签颜色
const getOrgTypeColor = (type) => {
  switch (type) {
    case 'company':
      return 'danger'
    case 'department':
      return 'warning'
    case 'team':
      return 'success'
    default:
      return 'info'
  }
}

// 获取树节点图标
const getNodeIcon = (type) => {
  switch (type) {
    case 'company':
      return OfficeBuilding
    case 'department':
      return FolderOpened
    case 'team':
      return Document
    default:
      return Document
  }
}

// 初始化
onMounted(async () => {
  await loadOrganizations()
})
</script>

<template>
  <div class="organization-management-container" v-if="canManageOrgs">
    <div class="page-header">
      <h2>组织管理</h2>
      <div>
        <el-button type="success" @click="createChildOrg" :disabled="!selectedOrgId">
          <el-icon><Plus /></el-icon>
          添加子组织
        </el-button>
        <el-button type="primary" @click="openCreateDialog()">
          <el-icon><Plus /></el-icon>
          新建组织
        </el-button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span class="loading-text">加载中...</span>
    </div>
    
    <div v-else class="content-wrapper">
      <div class="org-layout">
        <!-- 左侧组织树 -->
        <div class="org-tree-container">
          <div class="tree-header">
            <h3>组织架构</h3>
          </div>
          <el-scrollbar>
            <el-tree
              :data="treeData"
              :props="{ children: 'children', label: 'name' }"
              :highlight-current="true"
              :expand-on-click-node="false"
              node-key="id"
              default-expand-all
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <el-icon><component :is="getNodeIcon(data.type)" /></el-icon>
                  <span>{{ node.label }}</span>
                  <el-tag class="org-type-tag" size="small" :type="getOrgTypeColor(data.type)">
                    {{ getOrgTypeLabel(data.type) }}
                  </el-tag>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        
        <!-- 右侧数据表格 -->
        <div class="org-content">
          <div class="table-header">
            <h3>{{ selectedOrg ? selectedOrg.name + '的子组织' : '所有组织' }}</h3>
            <div class="search-box">
              <el-input
                v-model="searchText"
                placeholder="搜索组织名称或代码"
                prefix-icon
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
          
          <el-scrollbar>
            <el-table :data="filteredOrganizations" stripe style="width: 100%">
              <el-table-column prop="name" label="组织名称" min-width="120" :show-overflow-tooltip="true" />
              <el-table-column prop="code" label="组织代码" width="100" :show-overflow-tooltip="true" />
              <el-table-column prop="type" label="组织类型" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="getOrgTypeColor(scope.row.type)"
                  >
                    {{ getOrgTypeLabel(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="150" :show-overflow-tooltip="true" />
              <el-table-column prop="createdAt" label="创建时间" width="160">
                <template #default="scope">
                  {{ new Date(scope.row.createdAt).toLocaleString() }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="openEditDialog(scope.row)"
                      class="operation-button"
                    >
                      编辑
                    </el-button>
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="deleteOrganization(scope.row)"
                      class="operation-button"
                    >
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
      </div>
    </div>
    
    <!-- 组织编辑对话框 -->
    <el-dialog
      v-model="createOrgDialog"
      :title="editMode ? '编辑组织' : '创建组织'"
      width="50%"
    >
      <el-form :model="orgForm" label-width="100px">
        <el-form-item label="组织名称" required>
          <el-input v-model="orgForm.name" placeholder="请输入组织名称" />
        </el-form-item>
        
        <el-form-item label="组织代码" required>
          <el-input v-model="orgForm.code" placeholder="请输入组织代码" />
        </el-form-item>
        
        <el-form-item label="组织类型">
          <el-select v-model="orgForm.type" placeholder="请选择组织类型" style="width: 100%">
            <el-option
              v-for="item in orgTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上级组织">
          <el-select v-model="orgForm.parent" placeholder="请选择上级组织" style="width: 100%">
            <el-option
              label="无"
              value=""
            />
            <el-option
              v-for="org in organizations.filter(o => o.id !== orgForm.id)"
              :key="org.id"
              :label="org.name"
              :value="org.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input 
            v-model="orgForm.description" 
            type="textarea" 
            placeholder="请输入组织描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createOrgDialog = false">取消</el-button>
          <el-button type="primary" @click="saveOrganization" :loading="loading">
            {{ editMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
  <el-result
    v-else
    icon="error"
    title="权限不足"
    sub-title="很抱歉，您没有权限访问组织管理页面"
  >
    <template #extra>
      <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
    </template>
  </el-result>
</template>

<style scoped>
.organization-management-container {
  padding: 16px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  margin-bottom: 0;
}

.org-layout {
  display: flex;
  height: 100%;
  gap: 16px;
}

.org-tree-container {
  width: 280px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.tree-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.org-content {
  flex: 1;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.search-box {
  width: 240px;
}

.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 2px 0;
}

.tree-node .el-icon {
  margin-right: 4px;
  font-size: 16px;
}

.org-type-tag {
  margin-left: 8px;
  font-size: 9px;
  padding: 0 4px;
  height: 16px;
  line-height: 16px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.operation-button {
  margin-right: 0;
  min-width: 42px;
  padding: 4px 8px;
}

.loading-text {
  color: #909399;
  margin-top: 10px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* Tree scrollbar */
:deep(.el-tree) {
  padding: 8px;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

:deep(.el-scrollbar) {
  height: 100%;
}
</style> 